import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import store from '@/store/index'
import { h } from 'vue'

const layout = () => import(`@/views/layout.vue`)
const index = () => import('@/views/home/index.vue')
const category = () => import('@/views/category/index.vue')
const categorySub = () => import('@/views/category/sub.vue')
const goods = () => import('@/views/goods/index.vue')

const login = () => import('@/views/login/index.vue')
const callbackLogin = () => import('@/views/login/callback.vue') 
const cart = () => import('@/views/cart/index.vue')
const checkOut = () => import('@/views/menber/pay/checkOut.vue')
const pay = () => import('@/views/menber/pay/index.vue')
const result = () => import('@/views/menber/pay/result.vue')

const memberPayout = () => import('@/views/menber/layout.vue')
const membeIndex = () => import('@/views/menber/home/index.vue')
const memberOrder = () => import('@/views/menber/order/index.vue')
const orderDetai = () => import('@/views/menber/order/detail.vue')

const routes = [
  {
    path: '/',
    component: layout,
    children: [
      {
        path: '/',
        redirect: '/home'
      },
      {
        path: '/home',
        component: index
      },
      {
        path: '/category/:id',
        component: category
      },
      {
        path: '/category/sub/:id',
        component: categorySub
      },
      {
        path: '/product/:id',
        component: goods
      },
      {
        path:'/cart',
        component:cart
      },
      {
        path:'/member/checkout',
        component:checkOut
      },
      {
        path:'/member/pay',
        component:pay
      },
      {
        path:'/pay/result',
        component:result
      },
      {
        path:'/member',
        component:memberPayout,
        children:[
          {
            path:'/member',
            component:membeIndex
          },
          {
            path:'/member/order',
            // 创建一个RouterView容器形成嵌套关系
            component:{render:()=> h(<RouterView/>) },
            children:[
              {
                path:'',
                component:memberOrder
              },
              {
                path:':id',
                component:orderDetai
              }
            ]
          }
        ]
      }
    ]
  },
  {
    path:'/login',
    component:login
  },
  {
    path:'/login/callback',
    component:callbackLogin
  }

]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  // 保证每个页面刷新在顶部
  scrollBehavior() {
    // vue2 return {x:0,y:0}
    //  vue3 return {left:0,top:0}
    return { left: 0, top: 0 }
  }
})

// 路由守卫
router.beforeEach((to,from, next)=>{
  // 需要登录的路由：地址是以 /member 开头
  const { profile } = store.state.user
  if(!profile.token && to.path.startsWith('/member')){
    return next('/login?redirectUrl='+ encodeURIComponent(to.fullPath))
  }
  next()
})

export default router
